<?php

namespace App\HttpController\Admin;

use App\Model\NodesModel;
use EasySwoole\Validate\Validate;

class NodeController extends AuthController {

    public function index(){
        $model  = new NodesModel();
        $list   = $model->get();
        foreach ($list as $key=>&$item){
            $item['label'] = $item['name'];
            $item['value'] = $item['id'];
        }
        $list = $this->listToTree($list);
        return $this->writeJson(0,$list);
    }

    public function update(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $model = new NodesModel();
        $validate = new Validate();
        $validate->addColumn('name')->required('请填写节点名称');
        if(!$this->validate($validate)){
            return $this->writeJson(1, null, $validate->getError()->__toString());
        }
        $data['pid'] = (int)end($data['pitch']);
        if($data['id']){
            if($data['pid']){
                $_info = $model->select('pitch')->where('id',$data['pid'])->first();
                $data['pitch'] = array_merge($_info['pitch'],[(int)$data['pid']]);
            }else{
                $data['pitch'] = [0];
            }
            $model->update($data);
            return $this->writeJson(0,null,'编辑节点信息成功');
        }else{
            //新增
            if($data['pid']){
                $_info = $model->select('pitch')->where('id',$data['pid'])->first();
                $data['pitch'] = array_merge($_info['pitch'],[(int)$data['pid']]);
            }else{
                $data['pitch'] = [0];
            }
            $model->create($data);
            return $this->writeJson(0,$model->sql(),'新增节点信息成功');
        }
    }

    public function destroy(){
        $request = $this->request();
        $id = $request->getRequestParam('id');
        $model = new NodesModel();
        $model->destroy($id);
        return $this->writeJson(0);
    }

}
